package com.nuc.thread.threadpool;

import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description ForkJoinPool线程池
 * @createTime 2021年08月14日 11:28:00
 */
@Slf4j
public class Test4  {
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Integer invoke = forkJoinPool.invoke(new Mytask(5));
        System.out.println(invoke);
    }
}

/**
 * 计算从 1到n的和：体现的分支思想。myTask(5)=myTask(4)+5,myTask(4)=myTask(3)+4 ...以此类推
 */
@Slf4j
@ToString
class Mytask extends RecursiveTask<Integer>{

    private int n ;

    public Mytask(int n) {
        this.n = n;
    }

    @Override
    protected Integer compute() {
        if (n ==1){
            return 1;
        }
        Mytask t1 = new Mytask(n -1);
        t1.fork();
        log.debug("fork():{},{}",n,t1);

        Integer result = t1.join();
        log.debug("join():{}",n);
        return result+n;

    }
}
